'use strict'

import { BrowserWindow, ipcMain, screen } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
const path = require('path')
const windowOpacity = require('./windowOpacity.js')
let subWindow = null
let subWindowDict = {}

// 创建窗口
function createWindow(options) {
  let winW = screen.getPrimaryDisplay().workAreaSize.width
  let winH = screen.getPrimaryDisplay().workAreaSize.height
  subWindow = new BrowserWindow({
    title: '子窗口',
    width: winW <= 1240 ? winW : 1240,
    height: winH <= 730 ? winH : 730,
    show: true,
    center: true,
    frame: false, // 去掉窗口边框
    autoHideMenuBar: true, // 隐藏菜单栏
    titleBarStyle: 'customButtonsOnHover',
    simpleFullscreen: true,
    resizable: process.platform === 'darwin', // 可否调整大小
    movable: true, // 可否移动
    minimizable: true, // 可否最小化
    maximizable: true, // 可否最大化
    fullscreen: false, // MAC下是否可以全屏
    skipTaskbar: false, // 在任务栏中显示窗口
    acceptFirstMouse: true, // 是否允许单击页面来激活窗口
    transparent: process.platform === 'darwin', //允许透明
    closable: true,
    backgroundColor: '#fff',
    allowRunningInsecureContent: true, // 允许一个 https 页面运行 http url 里的资源
    webPreferences: {
      devTools: true, // 是否打开调试模式
      webSecurity: false, // 禁用安全策略
      allowDisplayingInsecureContent: true, // 允许一个使用 https的界面来展示由 http URLs 传过来的资源
      allowRunningInsecureContent: true, // 允许一个 https 页面运行 http url 里的资源
      webviewTag: true,
      plugins: true,
      // Use pluginOptions.nodeIntegration, leave this alone
      // See nklayman.github.io/vue-cli-plugin-electron-builder/guide/security.html#node-integration for more info
      // nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION
      enableRemoteModule: true,
      nodeIntegration: true,
      // preload: process.env.WEBPACK_DEV_SERVER_URL ? path.join(__dirname, '../public/preload.js') : `app://./preload.js`
      preload: process.env.WEBPACK_DEV_SERVER_URL ? path.join(__dirname, '../public/preload.js') : path.join(__dirname, 'preload.js')
    }
  })

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    // Load the url of the dev server if in development mode
    subWindow.loadURL(`${process.env.WEBPACK_DEV_SERVER_URL}/#/?redirect=${options.path}`)
    // await subWindow.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
    // if (!process.env.IS_TEST) subWindow.webContents.openDevTools()
  } else {
    createProtocol('app')
    // Load the child.html when not in development
    subWindow.loadURL(`app://./child.html/#/?redirect=${options.path}`)
  }

  subWindow
  .on('ready-to-show', () => { // 完成第一次绘制后显示
    // 程序界面淡入
    windowOpacity(subWindow)
  })
  .on('close', (event) => { // 监听关闭
    console.log('subWindow close:', event)
    // subWindow.send('close-window-render')
    // event.preventDefault()
  })
  .on('closed', () => {
    subWindow = null
  })
}

// 绑定事件
function bindEvent () {
  /**
   * 创建子窗口事件
   * @param {String} options/id 窗口id
   * @param {*} options/* 其他传参
   */
  ipcMain.on('createSubWindow', (event, options) => {
    console.info('createSubWindow Event:', event, options)
    options = options || {}
    let id = options.id
    if (subWindowDict[id] && !subWindowDict[id].isDestroyed()) {
      subWindowDict[id].focus()
    } else {
      delete subWindowDict[id]
      createWindow(options)
      subWindowDict[subWindow.webContents.id] = subWindow
    }
  })
}

/**
 * 窗口 - 关闭指定窗口
 * @param {Number} id 窗口id
 */
function close (id) {
  if (subWindowDict[id] && !subWindowDict[id].isDestroyed()) {
    subWindowDict[id].destroy()
    delete subWindowDict[id]
  }
}

/**
 * 窗口 - 关闭所有窗口
 */
function closeAll () {
  for (let id in subWindowDict) {
    if (subWindowDict[id] && !subWindowDict[id].isDestroyed()) {
      subWindowDict[id].destroy()
    }
  }
  subWindowDict = {}
}

// 暴露API
export default {
  init () {
    bindEvent()
  },
  close,
  closeAll
}
